package com.pignest.hotel.ui.reception;


import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zul.event.PagingEvent;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Booking;
import com.pignest.hotel.beans.BookingRoom;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.definition.BookingStatus;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.definition.RoomRepairStatus;
import com.pignest.hotel.definition.RoomUseStatus;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;
import com.pignest.hotel.util.WhereCreator;

@Deprecated
public class BookingModWindow extends Window  {

	/**
	 * 预定修改 同时可以直接入住
	 */
	private static final long serialVersionUID = 6777466362331283503L;

	private Booking selectBooking;
	
    private Textbox userName;//预定姓名
    private Textbox phoneNumber;//预定手机
    private Datebox estimatedDate;//预抵日期

    private Listbox preserve;
    private Label endTime;
    private Listbox liveDays;//预订天数
    private Label bookingLeaveTime;
    private Label bookingRooms;
    
    private Textbox qName;
    private Textbox qMobile;
    
    private Paging pagMember;
    private Listbox LivingMemListbox;
    
    private ReceptionService receptionService;
    private Member selectMember;
    private Checkbox isMember;
    private Label livingTip;

    private MemberService  memberService;
    
    private Listbox roomListbox;
    
    private Listbox roomTypeCount;
    
    private Textbox remark;
    
    private Checkbox isSetRoom;
    private Checkbox isSelf;
    private String []selectRoomTypeId;//选择房间类型ID
    private Room []selectRoom;
    private Paging pageRoom;
    

    
	public Booking getSelectBooking() {
		return selectBooking;
	}

	public void setSelectBooking(Booking selectBooking) {
		this.selectBooking = selectBooking;
	}
	
	public BookingModWindow()
	{
		receptionService =Services.getReceptionService();
		memberService = Services.getMemberService();
		
	}

	public void onCreate() 
	{
		userName = (Textbox)getFellow("userName");
		phoneNumber=(Textbox)getFellow("phoneNumber");
		estimatedDate=(Datebox)getFellow("estimatedDate");

		preserve=(Listbox)getFellow("preserve");
		endTime=(Label)getFellow("endTime");
		liveDays=(Listbox)getFellow("liveDays");
		bookingLeaveTime=(Label)getFellow("bookingLeaveTime");
		bookingRooms =(Label)getFellow("bookingRooms");
		LivingMemListbox =(Listbox)getFellow("LivingMemListbox");
		qName =(Textbox)getFellow("qName");
		qMobile=(Textbox)getFellow("qMobile");
		pagMember=(Paging)getFellow("pagMember");

		livingTip=(Label)getFellow("livingTip");
		remark=(Textbox)getFellow("remark");
		roomListbox=(Listbox)getFellow("roomListbox");
		roomTypeCount=(Listbox)getFellow("roomTypeCount");
		pageRoom =(Paging)getFellow("pageRoom");
		isSetRoom=(Checkbox)getFellow("isSetRoom");
		isMember=(Checkbox)getFellow("isMember");
		isSelf=(Checkbox)getFellow("isSelf");
		setModBookingInfo();
		pagMember.setTotalSize(memberService.find("from Member").size());
		final int PAGE_SIZE = pagMember.getPageSize();
		queryMember(0,PAGE_SIZE,true);
		pagMember.addEventListener("onPaging", new EventListener() {
		      public void onEvent(Event event) {
		        	PagingEvent pe = (PagingEvent) event;
		        	int pgno = pe.getActivePage();
		        	int start = pgno*PAGE_SIZE;
		        	queryMember(start,PAGE_SIZE,true);
		      	}
		    	});

		isSetRoom.addEventListener(Events.ON_CHECK, new EventListener(){
			 public void onEvent(Event event) {
				 setSetRoom();
			 }
		});
		queryRoomTypeStatic();
		queryRoom(0,pageRoom.getPageSize());
	}
	public void setModBookingInfo()
	{
		if(selectBooking!=null)
		{
			userName.setValue(selectBooking.getName());
			phoneNumber.setValue(selectBooking.getPhone());
			estimatedDate.setValue(selectBooking.getEstimatedTime());
			endTime.setValue(DateUtil.toFullString(selectBooking.getEndTime()));
			UIUtils.setSelectedItem(preserve, String.valueOf(selectBooking.getPreserve()));
			if(selectBooking.getEstimatedTime()!=null&&selectBooking.getLeaveTime()!=null)
			{
				String date1 = DateUtil.toFullString(selectBooking.getLeaveTime());
				String date2 = DateUtil.toFullString(selectBooking.getEstimatedTime());
				UIUtils.setSelectedItem(liveDays, String.valueOf(DateUtil.betweenDays(date2, date1)));
			}
			bookingLeaveTime.setValue(DateUtil.toFullString(selectBooking.getLeaveTime()));
		    if(selectBooking.getBookingRooms()!=null&&!selectBooking.getBookingRooms().isEmpty())
		    {
			   bookingRooms.setValue(selectBooking.getBookingRoomNames());
			   isSetRoom.setChecked(true);
		    }else
		    {
		    	isSetRoom.setChecked(false);
		    }
			if(selectBooking.getMember()!=null)
			{
				selectMember=selectBooking.getMember();
				isMember.setChecked(true);
			}
			remark.setValue(selectBooking.getRemark());
			
		}
	}
	public void queryMember(int start,int length,boolean isShowCurMember)
	{
		
		String sQname=qName.getValue();
		String sQmobile=qMobile.getValue();
		StringBuffer hql = new StringBuffer();
		hql.append(" from Member m where 1=1");
		if(sQname!=null&&!sQname.equals(""))
		{
			hql.append(" and m.name like '%").append(sQname).append("%'");
		}
		if(sQmobile!=null&&!sQmobile.equals(""))
		{
			hql.append(" and m.mobile like '%").append(sQmobile).append("%'");
		}
		if(this.selectBooking.getMember()!=null&&isShowCurMember)
		{
			hql.append(" and m.id ='").append(selectBooking.getMember().getId()).append("'");
		}
		List l =(List)memberService.find(hql.toString());
		int Total =l.size();
		pagMember.setTotalSize(Total);
		List<Member> mlist=memberService.QueryBy(hql.toString(), start, length);
		LivingMemListbox.getItems().clear();
		for(final Member m:mlist)
		{
			Listitem listitem = new Listitem();
			listitem.setValue(m.getId());
			listitem.setParent(LivingMemListbox);
	
			if(this.selectBooking.getMember()!=null&&isShowCurMember)
			{
				listitem.setCheckable(true);
			}
			listitem.appendChild(new Listcell(m.getName()));
			listitem.appendChild(new Listcell(m.getMobile()));
			if(m.getMemberLevel()!=null)
				listitem.appendChild(new Listcell(m.getMemberLevel().getMemberlevel()));
			else
				listitem.appendChild(new Listcell(""));
			listitem.appendChild(new Listcell(MoneyUtil.toString(m.getBalance())));
			listitem.appendChild(new Listcell(MoneyUtil.toString(m.getIntegral())));
			listitem.appendChild(new Listcell(m.getMail()));
			listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				   public void onEvent(Event event) throws Exception {
					   selectMember=m;
					   isMember.setChecked(true);
				   }
			   });

		}
	}
	public void modBooking()
	{
		boolean changeMember=false;
		boolean changeRoom=false;
		Date date =estimatedDate.getValue();
		String sPreserve=UIUtils.getSelectedValue(preserve);
		String sLiveDays = UIUtils.getSelectedValue(liveDays);
		String sUserName=userName.getValue();
		String sPhone=phoneNumber.getValue();
		if(this.selectBooking==null)
		{
			livingTip.setValue("无效的预定！");
			return ;
		}
		if (!check())
			return;
		StringBuilder MemberMessage = new StringBuilder();
		if(isChangeMember()){
			String msg="预定会员已变更是否变更！";
			MemberMessage.append("预定会员已变更是否变更！").append("\n");
			MemberMessage.append(selectMember.getName()).append("\n");
			if(UIUtils.confirm(msg))
			{
				changeMember=true;
			}
		}
		StringBuilder roomMessage = new StringBuilder();
		//预定房间
		if(isChangeRoom()){
			
			roomMessage.append("预定排房已变更是否变更").append("\n");
			roomMessage.append("原来预订客房为：").append(this.selectBooking.getBookingRoomNames()).append("\n");
			roomMessage.append("现在预订客房为:").append(showRoomNameInStr()).append("\n");
			
			if(UIUtils.confirm(roomMessage.toString()))
			{
				changeRoom=true;
			}else
			{
				isSetRoom.setChecked(false);
				bookingRooms.setValue(this.selectBooking.getBookingRoomNames());
			}
		}
		
	if (date.getTime() <= System.currentTimeMillis())
	{
		livingTip.setValue("选择的时间不合法:小于当前时间");
		return ;
	}

	
	int p = Utils.getInteger(sPreserve, 180);
	Date endTime = new Date(date.getTime() + p * 60 * 1000);
	
	//预订确认
	StringBuilder message = new StringBuilder();
	message.append("姓名: ").append(sUserName).append("\n");
	message.append("电话: ").append(sPhone).append("\n\n");
	if(changeMember)
	{
	  message.append(MemberMessage);
	}else
	{
		if(selectBooking.getMember()!=null)
		{
			message.append("会员: ").append(selectBooking.getMember().getName()).append("\n");
		}else
		{
			message.append("非会员预订\n");
		}
	}
	
	if(changeRoom)
	{
		message.append(roomMessage);
	}else
	{
		if (this.selectBooking.getBookingRoomNames() == null ) 
		{
			message.append("**不排房**\n");
		} else {
			message.append("预订客房 ").append(this.selectBooking.getBookingRoomNames()).append(" \n");
		}
	}
	
	message.append("预抵时间: ").append(DateUtil.toString(date)).append("\n");
	message.append("保留时间: ").append(DateUtil.toString(endTime));
	try {
		if (UIUtils.confirm(message.toString()))
		{
			selectBooking.setName(userName.getValue());
			selectBooking.setPhone(phoneNumber.getValue());
			selectBooking.setEstimatedTime(date);
			selectBooking.setEndTime(endTime);
			if(changeMember)
			   selectBooking.setMember(selectMember);
			selectBooking.setPreserve(p);
			selectBooking.setTime(new Date());
			selectBooking.setRemark(remark.getValue());
			selectBooking.setStatus(BookingStatus.ONGOING.name());
			
			int days = Utils.getInteger(sLiveDays, 1);
			selectBooking.setLeaveTime(new Date(date.getTime() + days * 24L * 3600 * 1000));
			receptionService.modBooking(selectBooking, selectRoom, changeRoom,isSetRoom.isChecked());
			livingTip.setValue("修改预定成功！");
			//setModBookingInfo();
			//service.addBooking(booking, roomIds);
		}

	} catch (Exception e) {
		livingTip.setValue(e.getMessage());
		e.printStackTrace();
		
	}
		
	}
	public boolean check() {
		String name = userName.getValue();
		String phone = phoneNumber.getValue();
		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(phone)) {
			userName.focus();
			UIUtils.alert("请输入预订者姓名和电话!");
			return false;
		}
		Date d = estimatedDate.getValue();
		if (!estimatedDate.isValid() || d == null || d.getTime() < System.currentTimeMillis() - 24L * 3600 * 1000) {
			estimatedDate.focus();
			UIUtils.alert("请输入合法的预订时间!, 预订日期晚于现在!");
			return false;
		}
		if(isSetRoom.isChecked())
		{
			if(this.selectBooking.getBookingRooms().isEmpty()&&selectRoom==null)
			{
				UIUtils.alert("请排房！");
				return false;
			}
		}
		return true;
	}
	public void calcTime() {
		Date date = estimatedDate.getValue();
		
		String sPreserve = UIUtils.getSelectedValue(preserve);
		String sEndTime = calcTime(date, Integer.parseInt(sPreserve));
		endTime.setValue(sEndTime);
		String sliveDays = UIUtils.getSelectedValue(liveDays);
		String leaveTime = calcTime(date, Integer.parseInt(sliveDays) * 24 * 60);
		bookingLeaveTime.setValue(leaveTime);
	}
	/**
	 * 计算时间(预订时间 -> 失效时间)
	 * */
	public static String calcTime(Date date ,int delay) {
		if (date == null || delay <= 0)
			return null;
		//Date d = DateUtil.parseDate(date, hms);
		return DateUtil.toString(new Date(date.getTime() + delay * 60L * 1000), "yyyy-MM-dd HH:mm");
	}
	//查询统计房间类型及间数
	 public void queryRoomTypeStatic(){
		 roomTypeCount.getItems().clear();
		   List lists = receptionService.queryRoomTypeStatic();
		   for(Iterator iter=lists.iterator();iter.hasNext();){   
              Object [] o=(Object[]) iter.next();   

              final String id =(String)o[0];
              String name =(String)o[1];
              Long count =(Long)o[2];
              Integer price =(Integer)o[3];
              Listitem listitem = new Listitem();
			   listitem.setValue(id);
			   listitem.setParent(roomTypeCount);
			   listitem.appendChild(new Listcell(""));
			   listitem.appendChild(new Listcell(name));
			   listitem.appendChild(new Listcell(String.valueOf(count)));
			   listitem.appendChild(new Listcell(MoneyUtil.toString(price)));
			   listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				   public void onEvent(Event event) throws Exception {
					   String s[]=UIUtils.getSeclectListId(roomTypeCount);
					   selectRoomTypeId =s;
					   queryRoom(0,pageRoom.getPageSize());
				   }
			   });
          }   
		   
	 }
	 public void queryRoom(int start,int pageSize){
		 roomListbox.getItems().clear();
		 WhereCreator w = new WhereCreator();
		 StringBuffer hql=new StringBuffer();
		 hql.append(" from Room b");
		 hql.append(" where b.repairStatus!='"+RoomRepairStatus.REPAIR+"'");
		 hql.append(" and b.useStatus!='").append(RoomUseStatus.DIRTY).append("'");
		 hql.append(" and b.liveStatus!='").append(RoomLiveStatus.FILLED).append("'");
		 if(selectRoomTypeId!=null){
			 String inStr=w.getInstr(selectRoomTypeId);
			 hql.append(" and b.type.id in(").append(inStr).append(")");
		 }
		 List l = receptionService.find(hql.toString());
		 int Total =l.size();
		 pageRoom.setTotalSize(Total);
		 List <Room> rooms =receptionService.queryPageHql(hql.toString(),start,pageSize);
		 for(final Room r:rooms){
			  Listitem listitem = new Listitem();
			   listitem.setValue(r);
			   listitem.setParent(roomListbox);
			   listitem.appendChild(new Listcell(""));
			   listitem.appendChild(new Listcell(r.getName()));
			   listitem.appendChild(new Listcell(r.getType().getName()));
			   listitem.appendChild(new Listcell(RoomLiveStatus.valueof(r.getLiveStatus()).getName()+RoomUseStatus.valueof(r.getUseStatus()).getName()));
			   listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				   public void onEvent(Event event) throws Exception {
					   selectRoom=getSeclectListRoom(roomListbox);
					   showRoomName();
					   isSetRoom.setChecked(true);
				   }
			   });
			   
		 }
		 
	 }
	 /**
		 * 获得列表中选中的房间
		 * ***/
		public static Room[] getSeclectListRoom(Listbox listbox){
			Set items = listbox.getSelectedItems();
			int count = listbox.getSelectedCount();
			Room[] rooms = new Room[count];
			Iterator iter= items.iterator();
			int i=0;
			while(iter.hasNext()){
				Listitem item=(Listitem)iter.next();
				rooms[i]=(Room)item.getValue();
				i++;
			}
		
			return rooms;
		}
		/**
		 * 显示选定房间名
		 * */
		public void showRoomName()
		{
			String inStr = "";
			if(selectRoom==null||selectRoom.length==0)
			{
				return ;
			}else
			{
				for (int i = 0; i < selectRoom.length; i++) {
					
					inStr = inStr  + selectRoom[i].getName() + ",";
				}
				if ("".equals(inStr) )
					return ;
				inStr = inStr.substring(0, inStr.length() - 1);
				bookingRooms.setValue(inStr);
				
			}
			
		}
		/**
		 * 显示选定房间名
		 * */
		public String showRoomNameInStr()
		{
			String inStr = "";
			if(selectRoom==null||selectRoom.length==0)
			{
				return "未排房";
			}else
			{
				for (int i = 0; i < selectRoom.length; i++) {
					
					inStr = inStr  + selectRoom[i].getName() + ",";
				}
				if ("".equals(inStr) )
					return "未排房";
				inStr = inStr.substring(0, inStr.length() - 1);
				return inStr;
				
			}
			
		}
		/**判断是否重新更新预定与会员之间的关系
		 * 
		 * @return
		 */
	public boolean isChangeMember()
	{
		if(isMember.isChecked()){
			if(this.selectBooking.getMember()!=null&&selectMember!=null)
			{
				if(!this.selectBooking.getMember().getId().equals(selectMember.getId()))
				{
					return true;
				}
			}else if(this.selectBooking.getMember()==null&&selectMember!=null)
			{
				return true;
			}
		}else
		{
			if(this.selectBooking.getMember()!=null)
			{
				return true;
			}
		}
		return false;
	}
	/**
	 * 判断是否更新排房
	 */
	public boolean isChangeRoom()
	{
		if(isSetRoom.isChecked()){
			if(this.selectBooking.getBookingRooms().isEmpty())//原来没有排房现在想排房
			{
				return true;
			}
			if(selectRoom!=null)//没有选择就想排房呀
			{
				return true;
			}
			if(this.selectBooking.getBookingRooms()!=null&&selectRoom!=null)//原来也有排房现在想改一改
			{
				if(this.selectBooking.getBookingRooms().size()!=selectRoom.length)//如果数量不一样，则一定不同
				{
					return true;
				}else//如果相同则比较如果新的一个不在原来之中则就有变化
				{
					boolean isExist =true;
					
					for (int i = 0; i < selectRoom.length; i++) {
						int diff=0;
						for (BookingRoom bookingRoom : this.selectBooking.getBookingRooms()) {
							if(!selectRoom[i].getId().equals(bookingRoom.getRoom().getId()))
							{
								diff=diff+1;
							}
						}
						if(diff==selectRoom.length)
						{
							isExist=false;
							i=selectRoom.length;
						}
					}
					if(!isExist){
						return true;
					}
				}
				
			}
		}else
		{
			if(!this.selectBooking.getBookingRooms().isEmpty())
			{
				return true;
			}
		}
		return false;
	}
	public void setSetRoom()
	{
		if(!isSetRoom.isChecked())
		{
			selectRoom=null;
			bookingRooms.setValue("未排房");
		}else
		{
			bookingRooms.setValue(selectBooking.getBookingRoomNames());
		}
	}
	
}
